import os
import shutil
import codecs

# 定义一个函数来复制并转换文件编码
def copy_and_convert_gb2312_to_utf8(src_file_path, dst_file_path):
    try:
        with codecs.open(src_file_path, 'r', encoding='gb2312') as source_file:
            content = source_file.read()
        with codecs.open(dst_file_path, 'w', encoding='utf-8') as target_file:
            target_file.write(content)
    except Exception as e:
        print(f"Error converting {src_file_path}: {str(e)}")

# 指定文件夹路径
folder_path = "D://code//xinchao_file//first//"

# 遍历文件夹中的文件
for root, dirs, files in os.walk(folder_path):
    for file in files:
        file_path = os.path.join(root, file)
        if file_path.lower().endswith(('.txt', '.c', '.h')):
            # 构建目标文件路径，用于保存UTF-8编码的文件
            utf8_file_path = file_path + ".utf8"
            copy_and_convert_gb2312_to_utf8(file_path, utf8_file_path)
            
            # 用新的UTF-8编码文件替换原文件
            shutil.move(utf8_file_path, file_path)
            print(f"Converted and replaced: {file_path}")

print("Conversion and replacement completed.")
